package com.yztstudy.Controller;

import com.yztstudy.Entity.User;
import com.yztstudy.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;


/**
 * User的表示层
 */

@Controller
@Scope("prototype") //spring注解的bean可以变成多例
@RequestMapping("/")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 跳转登录页面
     */
    @RequestMapping({"/", "/login"})
    public String login()
    {
        return "login";
    }

    /**
     * 登录
     */
    @PostMapping("/userLogin")
    public String userLogin(String userCode, User user, ModelMap model, HttpSession session)
    {
        //1.获取系统的验证码
        String checkcode = (String) session.getAttribute("checkcode");

        //2.对比
        if (checkcode.equalsIgnoreCase(userCode))
        {
            User loginUser = userService.login(user);
            if (loginUser != null)
            {
                session.setAttribute("loginUser", loginUser);
                return "redirect:/main.html";
            }else {
                model.addAttribute("message", "账号或密码错误!");
                return "login";
            }
        }else {
            model.addAttribute("message", "用户输入验证码错误!");
            return "login";
        }
    }

    /**
     * 退出，销户
     */
    @GetMapping("/userLogout")
    public String logout(HttpSession session)
    {
        //1.销户
        session.invalidate();

        //2.跳转到登录界面
        return "login";
    }

}
